import React, { useRef, useState } from 'react';
import PageTitle from '@/components/PageTitle';
import { Button, Form, Input, message, Select, DatePicker, Modal } from 'antd';
import Tables from '@/hoc/Tables';
import Models from '@/components/Models';
import { Orignizers } from './index.d';
import styles from './index.less';
import { INSTITUTION_LIST } from '@/services/list';
import moment from 'moment';
import { BasicLayoutProps } from '@/layouts/BasicLayout';
import AddressSelect from '@/components/AddressSelect';
import { setAddressList, setAddressValue } from '@/utils/utils';
import { disableOrEnablePress, insertPressOrganization, updatePressOrganization } from '@/services/institution';
import { TableProps } from '@/global.d';
const { Option } = Select;

const arrType: string[] = ['印吧', '印社', '企业', '院校', '学校', '事业单位'];

const Institution: React.FC<BasicLayoutProps> = props => {
  const childRef = useRef<TableProps | any>();
  let title = props?.route?.name;
  let columns: any[] = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '单位',
      dataIndex: 'company',
      key: 'company',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (_: number, text: Orignizers) => <span>{arrType[text.type - 1]}</span>,
    },
    {
      title: '建立时间',
      dataIndex: 'setupTime',
      key: 'setupTime',
    },
    {
      title: '所在省，市',
      dataIndex: 'provinceName',
      key: 'cityName',
      render: (text: Orignizers) => (
        <span>
          {text?.provinceName}
          {text?.cityName}
          {text?.regionName}
        </span>
      ),
    },
    {
      title: '操作',
      width: 250,
      render: (item: any) => (
        <div className="operation">
          <span
            onClick={() => {
              onEdit(item, 1);
            }}>
            查看
          </span>
          <span
            onClick={() => {
              onEdit(item, 0);
            }}>
            修改
          </span>
          <span
            onClick={() => {
              onisDis(item, !item?.state ? 1 : 0);
            }}>
            {!item?.state ? '禁用' : '启用'}
          </span>
        </div>
      ),
    },
  ];
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(false);
  const [issee, setIssee] = useState<boolean>(false);
  const [itemObj, setItemObj] = useState<any>({});

  /**
   * 添加展览
   */
  const onChange = () => {
    setVisible(true);
  };

  /**
   * 弹窗关闭
   */
  const handleCancel = () => {
    setVisible(false);
    setItemObj({});
    form.resetFields();
    setIssee(false);
  };

  /**
   * 提交
   * @param values
   */
  const onFinish = (values: Orignizers) => {
    let value: any = {
      ...values,
      setupTime: moment(values?.setupTime).format('YYYY-MM-DD'),
      id: itemObj?.id,
      ...setAddressValue(values.code1 ?? []),
    };

    delete value.code1;

    if (!itemObj?.id) {
      insertPressOrganization(value).then((res: any) => {
        if (res?.responseCode == 200) {
          message.success('保存成功');
          handleCancel();
          childRef.current.setQuery({});
        } else {
          message.success('保存失败');
        }
      });
    } else {
      updatePressOrganization(value).then((res: any) => {
        if (res?.responseCode == 200) {
          message.success('编辑成功');
          handleCancel();
          childRef.current.setQuery({});
        } else {
          message.success('编辑失败');
        }
      });
    }
  };

  /**
   * 编辑
   * @param item
   */
  const onEdit = (item: Orignizers, id: number) => {
    setItemObj(item);
    form.setFieldsValue({
      ...item,
      code1: setAddressList(item),
      setupTime: item?.setupTime ? moment(item?.setupTime) : undefined,
    });
    if (id) {
      setIssee(true);
    }
    onChange();
  };

  /**
   * 删除
   */
  const onisDis = (item: any, state: number) => {
    Modal.confirm({
      title: `${!state ? '启用' : '停用'}提示`,
      content: `确定要${!state ? '启用' : '停用'}当前数据吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        disableOrEnablePress({ id: item?.id, state }).then((res: any) => {
          if (res?.responseCode == 200) {
            message.success(`${state ? '禁用' : '启用'}成功`);
            childRef.current.setQuery({});
          } else {
            message.success(`${state ? '禁用' : '启用'}失败`);
          }
        });
      },
    });
  };

  return (
    <div className={styles.regimePage}>
      <PageTitle
        title={title}
        right={
          <Button className="btn_red" onClick={onChange}>
            添加
          </Button>
        }
      />
      <div className="regime_table">
        <Tables childRef={childRef} url={INSTITUTION_LIST} columns={columns} />
      </div>
      <Models className="add_regimes" width="540px" visible={visible} handleCancel={handleCancel}>
        <Form labelAlign="left" {...layout} form={form} name="control-hooks" onFinish={onFinish}>
          <div className="add_user">{issee ? '查看·印吧印社' : itemObj?.id ? '修改·印吧印社' : '新增·印吧印社'}</div>
          <div className="add_user_form">
            <Form.Item label="名称" name="name" required={false} rules={[{ required: true, message: '请输入印机构名称' }]}>
              <Input disabled={issee} size="large" className="regime_input" allowClear placeholder="请输入印机构名称" />
            </Form.Item>
            <Form.Item label="所属单位" name="company" required={false} rules={[{ required: true, message: '请输入所属单位名称' }]}>
              <Input disabled={issee} size="large" className="regime_inputs" allowClear placeholder="请输入所属单位名称" />
            </Form.Item>
            <Form.Item label="类型" name="type" required={false} rules={[{ required: true, message: '请选择类型' }]}>
              <Select disabled={issee} size="large" className="regime_input" placeholder="请选择类型" allowClear>
                {['印吧', '印社', '企业', '院校', '学校', '事业单位'].map((el, index) => (
                  <Option key={index + '_id81176'} value={index + 1}>
                    {el}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item label="建立时间" name="setupTime" required={false} rules={[{ required: true, message: '请选择建立时间' }]}>
              <DatePicker disabled={issee} size="large" className="regime_input" placeholder="请选择建立时间" />
            </Form.Item>
            <Form.Item label="所在省市" name="code1" required={false} rules={[{ required: true, message: '请选择所在省市' }]}>
              <AddressSelect disabled={issee} width={100} size="large" />
            </Form.Item>
            <Form.Item label=" " colon={false} name="address" required={false}>
              <Input disabled={issee} size="large" className="regime_inputs" allowClear placeholder="请输入详细地址" />
            </Form.Item>
            <Form.Item label="地图坐标" name="longitude" required={false}>
              <Input disabled={issee} prefix={<span>经度：</span>} size="large" className="regime_inputs" allowClear placeholder="" />
            </Form.Item>
            <Form.Item label=" " colon={false} name="latitude" required={false}>
              <Input disabled={issee} prefix={<span>纬度：</span>} size="large" className="regime_inputs" allowClear placeholder="" />
            </Form.Item>
          </div>
          <div className="hr"></div>
          {issee ? (
            <div className="regime_btns">
              <Button className="btn_cold" onClick={handleCancel}>
                关闭
              </Button>
            </div>
          ) : (
            <div className="regime_btns">
              <Button className="btn_cold" onClick={handleCancel}>
                取消
              </Button>
              <Button className="btn_red" htmlType="submit">
                提交
              </Button>
            </div>
          )}
        </Form>
      </Models>
    </div>
  );
};

export default Institution;
